﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Web;
using WebChart;

namespace TSharp.Core.AppBox.Handlers
{
    public class ImageHandler : DynamicImageHandler
    {
        public ImageHandler(HttpContext context, string requestType, string url, string pathTranslated)
            : base(context, requestType, url, pathTranslated)
        { }

        private static WebChart.ChartEngine engine = new WebChart.ChartEngine();
        static ImageHandler()
        {
            //BorderStyle="Groove" BorderColor="White" Width="480px" Height="300px" HasChartLegend="False" TopPadding="15"


            var line = engine.Border;
            line.Color = Color.Blue;



            //<ChartTitle ForeColor="White" Text="WebChart Control" Font="Tahoma, 10pt, style=Bold"></ChartTitle>
            var t = engine.Title = new ChartText();
            t.ForeColor = Color.White;
            t.Text = "性能监视";
            t.Font = new Font("Tahoma", 10, FontStyle.Bold);


            //<XTitle ForeColor="Black" Font="Tahoma, 8pt"></XTitle>
            engine.YTitle = new ChartText();
            engine.YTitle.Font = new Font("Tahoma", 8);
            engine.YTitle.ForeColor = Color.Black;
            engine.YTitle.Text = "Y标题";


            //<Background Type="LinearGradient" Angle="90" StartPoint="0, 0" ForeColor="#80FF80" EndPoint="100, 300" Color="CornflowerBlue" HatchStyle="ZigZag"></Background>
            var interior = engine.Background;
            interior.Type = InteriorType.LinearGradient;
            interior.Angle = 90;
            interior.StartPoint = new Point(0, 0);
            interior.ForeColor = Color.FromArgb(0x80, 0xff, 0x80);
            interior.EndPoint = new Point(100, 300);
            interior.Color = Color.CornflowerBlue;
            interior.HatchStyle = HatchStyle.ZigZag;

            //<Border StartCap="Flat" EndCap="Flat" Width="0" DashStyle="Solid" Color="CornflowerBlue" LineJoin="Miter"></Border>
            line = engine.Border;
            line.StartCap = LineCap.Flat;
            line.EndCap = LineCap.Flat;
            line.Width = 1;
            line.DashStyle = DashStyle.Solid;
            line.Color = Color.CornflowerBlue;
            line.LineJoin = LineJoin.Miter;

            //<PlotBackground Type="LinearGradient" Angle="90" StartPoint="0, 0" ForeColor="#FFFFC0" EndPoint="100, 300" Color="White" HatchStyle="Shingle"></PlotBackground>
            interior = engine.PlotBackground;
            interior.Type = InteriorType.LinearGradient;
            interior.Angle = 90;
            interior.StartPoint = new Point(0, 0);
            interior.ForeColor = Color.FromArgb(0xff, 0xff, 0xc0);
            interior.EndPoint = new Point(100, 300);
            interior.Color = Color.White;
            interior.HatchStyle = HatchStyle.Shingle;

            //<YAxisFont ForeColor="Black" Font="Tahoma, 8pt"></YAxisFont>
            t = engine.XAxisFont;
            t.ForeColor = Color.Black;
            t.Text = "性能监视";
            t.Font = new Font("Tahoma", 8, FontStyle.Bold);
            engine.YAxisFont = t;
            //<XAxisFont ForeColor="Black" Font="Tahoma, 8pt"></XAxisFont>
            t = new ChartText();
            t.ForeColor = Color.Black;
            // t.Text = "性能监视";
            t.Font = new Font("Tahoma", 8, FontStyle.Bold);

            //<Legend Width="100" Font="Tahoma, 6pt">
            //    <Border StartCap="Flat" EndCap="Flat" Width="0" DashStyle="Solid" Color="Black" LineJoin="Miter"></Border>
            //    <Background Type="Solid" StartPoint="0, 0" ForeColor="Black" EndPoint="100, 100" Color="#FFFFC0" HatchStyle="Shingle"></Background>
            //</Legend>
            var legend = engine.Legend;
            legend.Width = 200;
            legend.Font = new Font("Tahoma", 10, FontStyle.Bold);
            legend.Border.StartCap = LineCap.Flat;
            legend.Border.EndCap = LineCap.Flat;
            legend.Border.Width = 0;
            legend.Border.DashStyle = DashStyle.DashDot;
            legend.Border.Color = Color.Black;
            legend.Border.LineJoin = LineJoin.Miter;
            legend.Position = LegendPosition.Left;

            interior = legend.Background;
            interior.Type = InteriorType.Solid;
            interior.Angle = 90;
            interior.StartPoint = new Point(0, 0);
            interior.ForeColor = Color.Black;
            interior.EndPoint = new Point(100, 500);
            interior.Color = Color.FromArgb(0xff, 0xff, 0xc0);
            interior.HatchStyle = HatchStyle.Trellis;
            interior.CenterColor = Color.Blue;



            engine.HasChartLegend = true;

            engine.TopChartPadding = 15;
            engine.Size = new Size(1000, 600);

            engine.LeftChartPadding = 10;
            engine.GridLines = GridLines.Both;
            //  engine.ShowTitlesOnBackground = true;
            engine.ShowXValues = true;
            //  engine.ShowYValues = true;
            engine.XTicksInterval = 30;
            //  engine.YCustomStart = -1;
            // engine.YCustomEnd = 5;

        }
        protected override Bitmap GetBitmap(HttpContext context)
        {
            try
            {
                engine.YCustomEnd = engine.YCustomStart = 0;
                Refresh(engine);
                return engine.GetBitmap();
            }
            catch (Exception ex)
            {
                return engine.GenerateErrorBitmap(ex.Message);
            }
        }

        private ChartPointCollection GetDefaultData()
        {
            ChartPointCollection d = new ChartPointCollection();
            for (int i = 0, n = PerfmonHtttpHandler.xLength; i < n; i++)
            {
                d.Add(new ChartPoint(DateTime.Now.Ticks + "", 0));
            }
            return d;
        }

        private void Refresh(ChartEngine engine)
        {
            var r = new Random();
            if (engine.Charts == null || engine.Charts.Count == 0)
            {
                if (engine.Charts == null)
                    engine.Charts = new ChartCollection(engine);
                foreach (var p in PerfmonHtttpHandler.Values)
                {
                    var color = RandomColor(p.Key.CounterName);
                    var c = new WebChart.LineChart(GetDefaultData(), color);
                    c.Name = p.Key.CounterName;

                    c.ShowLegend = true;
                    c.Legend = p.Key.CounterName;
                    //图例的填充颜色
                    c.Fill.Color = color;
                    c.Fill.CenterColor = color;
                    c.Fill.ForeColor = Color.Black;

                    c.ShowLineMarkers = true;
                    c.LineMarker.BorderColor = color;
                    c.LineMarker.Color = color;
                    c.LineMarker.Size = 5;
                    c.Line.Width = 1;
                    c.Line.StartCap = LineCap.Flat;
                    c.Line.EndCap = LineCap.Flat;
                    // AdjustableArrowCap myArrow = new AdjustableArrowCap(4, 4, false);
                    //CustomLineCap customArrow = myArrow;
                    c.Line.EndCap = LineCap.Flat;
                    // c.Line.CustomEndCap = myArrow;
                    c.Line.DashStyle = DashStyle.Solid;


                    c.DataLabels.Visible = true;
                    //c.DataLabels.NumberFormat = "C";
                    c.DataLabels.ForeColor = Color.CornflowerBlue;

                    engine.Charts.Add(c);
                }
            }
            foreach (var p in PerfmonHtttpHandler.Values)
            {
                Chart c = engine.Charts.FindChart(p.Key.CounterName);
                ChartPointCollection d = c.Data;
                c.ShowLegend = true;

                #region 取值

                //d.Add(new ChartPoint(DateTime.Now.Ticks + "", p.Value[p.Value.Count - 1]));
                try
                {
                    var counter = p.Key;
                    if (PerformanceCounterCategory.InstanceExists(counter.InstanceName, counter.CategoryName))
                    {
                        //v.Add(p.Key.NextValue());
                        d.Add(new ChartPoint(DateTime.Now.Ticks + "", p.Key.NextValue()));
                    }
                    else
                    {
                        d.Add(new ChartPoint(DateTime.Now.Ticks + "", 0));
                        Debug.WriteLine(string.Format(@"无计数器：{0}\{1}\{2}", counter.InstanceName, counter.CategoryName, counter.CounterName));
                    }
                }
                catch (Exception ee)
                {
                    Debug.WriteLine("计数器取值错误 >>> " + ee.Message);
                    //v.Add(r.Next(99));
                }
                #endregion

                if (c.Data.Count > PerfmonHtttpHandler.xLength)
                    c.Data.RemoveAt(0);


            }


        }
        static System.Collections.Generic.Dictionary<string, Color> Colors = new System.Collections.Generic.Dictionary<string, Color>();
        Color RandomColor(string key)
        {
            Debug.WriteLine(key);
            if (!Colors.ContainsKey(key))
            {
                var r = new Random();
                Colors.Add(key, all[0]);
                all.RemoveAt(0);
            }
            return Colors[key]; ;
        }
        static List<Color> all = new List<Color>(new Color[] { Color.Red, Color.Blue, Color.Green, Color.Black, Color.LightGray });
    }
}